import io
import sys
import threading
from typing import Callable


class TextRedirector(io.StringIO):
    """用于将标准输出重定向到 QScintilla 编辑器"""

    def __init__(self, output: Callable[..., str]):
        super().__init__()
        self.output = output

    def write(self, text):
        self.output(text)


def _run_script_worker(code: str, output: Callable[..., str]):
    """运行代码（示例功能）"""
    # 获取编辑器中的代码
    # 重定向 stdout 到 TextRedirector（即输出区域）
    redirector = TextRedirector(output)
    sys.stdout = redirector  # 将标准输出重定向到 TextRedirector
    try:
        exec(code)
    except Exception as e:
        output(f"Error: {str(e)}")

    output("\nScript finished")


def run_script(code: str, output: Callable[..., str]) -> None:
    t = threading.Thread(target=_run_script_worker, args=(code, output))
    t.start()
